package cn.xieyang.debugger;

public class SqlTableNameExtractor {

    /**
     * 从 SQL 语句中提取表名
     * @param strRealSql SQL 语句
     * @param sqlType SQL 类型 (SELECT, UPDATE, INSERT, DELETE)
     * @return 提取的表名，如果无法提取则返回 null
     */
    public static String extractTableName(String strRealSql, String sqlType) {
        if (strRealSql == null || sqlType == null) {
            return null;
        }

        String sql = strRealSql.trim();
        String upperSqlType = sqlType.toUpperCase();
        String lowerSql = sql.toLowerCase();

        try {
            if ("SELECT".equals(upperSqlType)) {
                // 查找 FROM 关键字位置（不区分大小写）
                int fromIndex = lowerSql.indexOf("from");
                if (fromIndex == -1) return null;

                // 找到 FROM 后的第一个非空格字符
                int tableStartIndex = -1;
                for (int i = fromIndex + 4; i < sql.length(); i++) {
                    if (!Character.isWhitespace(sql.charAt(i))) {
                        tableStartIndex = i;
                        break;
                    }
                }
                if (tableStartIndex == -1) return null;

                // 找到表名的结束位置（第一个空格或语句结束）
                int tableEndIndex = -1;
                for (int i = tableStartIndex; i < sql.length(); i++) {
                    if (Character.isWhitespace(sql.charAt(i))) {
                        tableEndIndex = i - 1;
                        break;
                    }
                }
                if (tableEndIndex == -1) tableEndIndex = sql.length() - 1;

                // 提取表名并去除反引号
                String tableName = sql.substring(tableStartIndex, tableEndIndex + 1).trim();
                return tableName.replace("`", "");

            } else if ("UPDATE".equals(upperSqlType)) {
                // 查找 UPDATE 关键字位置（不区分大小写）
                int updateIndex = lowerSql.indexOf("update");
                if (updateIndex == -1) return null;

                // 找到 UPDATE 后的第一个非空格字符
                int tableStartIndex = -1;
                for (int i = updateIndex + 6; i < sql.length(); i++) {
                    if (!Character.isWhitespace(sql.charAt(i))) {
                        tableStartIndex = i;
                        break;
                    }
                }
                if (tableStartIndex == -1) return null;

                // 查找 SET 关键字位置（不区分大小写）
                int setIndex = lowerSql.indexOf("set", tableStartIndex);
                if (setIndex == -1) return null;

                // 提取表名并去除反引号
                String tableName = sql.substring(tableStartIndex, setIndex).trim();
                return tableName.replace("`", "");

            } else if ("INSERT".equals(upperSqlType)) {
                // 查找 INTO 关键字位置（不区分大小写）
                int intoIndex = lowerSql.indexOf("into");
                if (intoIndex == -1) return null;

                // 找到 INTO 后的第一个非空格字符
                int tableStartIndex = -1;
                for (int i = intoIndex + 4; i < sql.length(); i++) {
                    if (!Character.isWhitespace(sql.charAt(i))) {
                        tableStartIndex = i;
                        break;
                    }
                }
                if (tableStartIndex == -1) return null;

                // 查找左括号位置
                int parenIndex = sql.indexOf('(', tableStartIndex);
                if (parenIndex == -1) return null;

                // 提取表名并去除反引号
                String tableName = sql.substring(tableStartIndex, parenIndex).trim();
                return tableName.replace("`", "");

            } else if ("DELETE".equals(upperSqlType)) {
                // 查找 FROM 关键字位置（不区分大小写）
                int fromIndex = lowerSql.indexOf("from");
                if (fromIndex == -1) return null;

                // 找到 FROM 后的第一个非空格字符
                int tableStartIndex = -1;
                for (int i = fromIndex + 4; i < sql.length(); i++) {
                    if (!Character.isWhitespace(sql.charAt(i))) {
                        tableStartIndex = i;
                        break;
                    }
                }
                if (tableStartIndex == -1) return null;

                // 找到表名的结束位置（第一个空格或语句结束）
                int tableEndIndex = -1;
                for (int i = tableStartIndex; i < sql.length(); i++) {
                    if (Character.isWhitespace(sql.charAt(i))) {
                        tableEndIndex = i - 1;
                        break;
                    }
                }
                if (tableEndIndex == -1) tableEndIndex = sql.length() - 1;

                // 提取表名并去除反引号
                String tableName = sql.substring(tableStartIndex, tableEndIndex + 1).trim();
                return tableName.replace("`", "");

            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {
        // 测试用例
        String[] testSqls = {
                "SELECT * FROM users WHERE id = 1",
                "UPDATE products SET price = 100 WHERE id = 5",
                "INSERT INTO orders (id, name) VALUES (1, 'test')",
                "DELETE FROM customers WHERE id = 10",
                "SELECT name, age FROM employees",
                "UPDATE my_table SET value = 1",
                "INSERT my_table (col1, col2) VALUES (1, 2)",
                "DELETE my_table WHERE id = 1",
                "SELECT * FROM `table_name` WHERE id = 1", // 有反引号
                "select * from   my_table  where id = 1", // 有多余空格
        };

        String[] sqlTypes = {
                "SELECT", "UPDATE", "INSERT", "DELETE",
                "SELECT", "UPDATE", "INSERT", "DELETE",
                "SELECT", "SELECT"
        };

        for (int i = 0; i < testSqls.length; i++) {
            String tableName = extractTableName(testSqls[i], sqlTypes[i]);
            System.out.println("SQL: " + testSqls[i]);
            System.out.println("类型: " + sqlTypes[i]);
            System.out.println("表名: " + tableName);
            System.out.println("---");
        }
    }
}
